from django import template
register = template.Library()

from django.utils.html import format_html
from myadmin.models import *
from django.core.urlresolvers import reverse


# 自定义标签 分页功能
@register.simple_tag
def showpage(count,request):
    # count=int(count)
    # 获取页面中的搜索条件 &types=phone&keywords=11
    data = request.GET.dict()  
    u = ''
    for k,v in data.items():
        if k != 'page':
            u += '&{k}={v}'.format(k=k,v=v)
    print(u)
    # 获取当前页码数
    p = int(request.GET.get('page',1))
    # 开始页
    begin = p-4
    # 结束页
    end = p+5
    # 判断如果当前页 小于5
    if p < 5:
        # 则开始页为1
        begin = 1
        # 结束页为10
        end = 10
    # 判断如果总页数小于10
    if count<10:
        begin=1
        end = count

    # 当前页如果大于总页数-5
    if p > count-5:
        # 则开始页为总页数-9
        begin = count - 9
        # 结束页为总页数
        end = count
    
    # 判断如果开始页 小于等于 0,则开始页为1
    if begin <= 0:
        begin = 1

    s = ''
    s += '<li><a href="?page=1'+u+'">首页</a></li>'

    
    # 上一页
    if p == 1:
        s += '<li class="am-disabled"><a href="?page=1'+u+'">«</a></li>'
    else:
        s += '<li><a href="?page='+str(p-1)+u+'">«</a></li>'

    
    for x in range(begin,end+1):
        if p == x:
            s += '<li class="am-active"><a href="?page='+str(x)+u+'">'+str(x)+'</a></li>'
        else:
            s += '<li><a href="?page='+str(x)+u+'">'+str(x)+'</a></li>'


    # 下一页
    if p == count:
        s += '<li class="am-disabled"><a href="?page='+str(count)+u+'">»</a></li>'
    else:
        s += '<li><a href="?page='+str(p+1)+u+'">»</a></li>'
    s += '<li><a href="?page='+str(count)+u+'">尾页</a></li>'

    return format_html(s)

# 自定义标签 头部导航
@register.simple_tag
def shownav():
    # 获取所有的二级列表
    erlist=Types.objects.exclude(pid=0)
    # 导航栏的内容
    nav=''
    for x in erlist:
        nav+='''
            <li class="layout-header-nav-item">
        <a href="{url}" class="layout-header-nav-link">{name}</a></li>
        '''.format(name=x.name,url=reverse('myhome_list',args=(x.id,)))
    # 返回解析的页面
    return format_html(nav)

# 自定义标签 乘法运算
@register.simple_tag
def showtotal(num,price):
    res=num*price
    return '%.2f'%res
